package com.wzf.filter;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
//设置高优先级
@Order(1)
@Slf4j
public class PrintRequstBodyLogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String method = httpServletRequest.getMethod();
        String header = httpServletRequest.getHeader("Content-Type");
        if ("POST".equalsIgnoreCase(method) && StringUtils.isNotBlank(header)&&"application/json".
                equalsIgnoreCase(header)){
            BufferedRequestWrapper cachedBodyHttpServletRequest = new BufferedRequestWrapper(httpServletRequest);
            String requestBody = cachedBodyHttpServletRequest.getRequestBody();
            log.info("请求的url为"+httpServletRequest.getRequestURI()+"\n"+"请求体为:"+requestBody);
            filterChain.doFilter(cachedBodyHttpServletRequest, servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

}
